//
//  EvidenceBrowseViewController.m
//  evidenceGather
//
//  Created by 继伟 王 on 13-8-17.
//  Copyright (c) 2013年 无. All rights reserved.
//

#import "EvidenceBrowseViewController.h" 
#import "UserVO.h"
#import "SystemUtils.h"
#import "AddViewController.h"
#import "Combox.h"
#import "MDProject.h"
#import "MDProvince.h"
#import "MDProbCls.h"
#import "MDGather.h"
#import "ProjectVO.h"
#import "ProviceVO.h"
#import "ProblemClassVO.h"
#import "SinaLabel.h"
#import "MyLabel.h"
#import "KxMenu.h"
#import "DefGatherCode.h"
#import "DefButton.h"
#import "PhotoDataSource.h"
#import "TokDocManageUtilities.h"
#import "KTPhotoScrollViewController.h"
#import "PopoverViewController.h"
#import "FPPopoverController.h"

#import "FPPopoverController.h"

#import "PropoverProvViewController.h"
#import "ProjPoverProjViewController.h"
#import "LocationManager.h"

#import "RequestTccInfo.h"
#import "ASIFormDataRequest.h"
#import "ZipArchive.h"
#import "JSNotifier.h"


#import "MDUser.h"


@interface AddViewController ()

-(void) drawProbLabel:(UIImage *) image projCode:(NSString *) selectProjCode clsCode:(NSString *) selectClsCode fileType:(int) fileType;

-(void) addImage2View:(UIImage *) image imageCount:(float) count  gatherCode:(NSString *)gatherCode;
-(void) addRadio2View:(NSString *)radioFilePath radioCount:(float)radioCount;

@end


@implementation EvidenceBrowseViewController

@synthesize userVO;
@synthesize mdProbCls;
@synthesize mdProject;
@synthesize mdProvince;
@synthesize mdGather;

@synthesize curSelectPjectCode;
@synthesize curSelectPjectName;
@synthesize curSelectProvCode;

@synthesize probClsKeyValue;
@synthesize projKeyKeyValue;
@synthesize provKeyValue;
@synthesize location;

@synthesize dd1;
@synthesize dd2;

@synthesize popoverCtrl;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}


-(void)drawProbLabel{
    NSMutableDictionary *probClsDict=[mdProbCls qryProClsByPkUser:userVO.loginuser];
    if(probClsDict!=nil){
        NSArray *probClsVOs=[probClsDict allValues]; 
        float lineHeight=45;
        NSMutableDictionary *probNumByProj=[mdGather qryGatherRecourdCountByPk:curSelectPjectCode];
        for(int i=0;i<[probClsDict count];i++){
            float orginalY=57+(i/2)*lineHeight;
            float orginalX=50+(i%2)*300;
            ProblemClassVO *probClsVO = [probClsVOs objectAtIndex:i];
            SinaLabel  *sinaLabel=[[SinaLabel alloc] initSinaLabel:CGRectMake(orginalX, orginalY, 400, lineHeight) titleText:[probClsVO pcname] count:5];
            int orginY=orginalY+110;
            int orginX=sinaLabel.textLabel.frame.size.width+orginalX;
        
            //添加小图标
            MyLabel *hintLabel=[[MyLabel alloc] initWithFrame:CGRectMake(orginX, orginY, 30,30)];
            UIImage *image =[UIImage imageNamed:@"number-icon_bg.png"];
            [hintLabel setBackgroundColor:[UIColor colorWithPatternImage:image]];
            hintLabel.textColor=[UIColor whiteColor];
            NSString  *count=@" 0";
            if(probNumByProj!=nil){
                count=[probNumByProj objectForKey:[probClsVO pccode]]; 
            }
            hintLabel.text=count;
            [hintLabel setFont:[UIFont fontWithName:@"Helvetica-Bold" size:15]];
            [hintLabel setLabelCode:[probClsVO pccode]];
            [hintLabel setLabelUser:[userVO loginuser]];
            [hintLabel setDelegate:self];
            [hintLabel setSuperCtrl:self];
            [_contentScrollView  addSubview:hintLabel];
        
            sinaLabel.delegate=self;
            [_probClsLabel addSubview:sinaLabel];
        }
    }
}
#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad]; 
    //初始化信息
    if(mdProject==nil){ //项目数据库句柄
        mdProject=[[MDProject alloc] init];
    }
    if(mdProvince==nil){//省份数据库句柄
        mdProvince=[[MDProvince alloc] init];
    }
    if(mdProbCls==nil){//问题类别数据库句柄
        mdProbCls=[[MDProbCls alloc] init];
    }
    
    if(mdGather==nil){//数据采集数据库句柄
        mdGather=[[MDGather alloc] init];
    }
    
    //设置滚动区背景
    UIImage *image =[UIImage imageNamed:@"bg.png"];
    [_contentScrollView setBackgroundColor:[UIColor colorWithPatternImage:image]];
    
    location=[[LocationManager alloc] init];
    //省份信息 
    self.curSelectProvCode=location.provCode;
    if(self.curSelectProvCode!=nil){
        ProviceVO *curProviceVO=[mdProvince qryProvinceByPk:curSelectProvCode];
        if(curProviceVO!=nil){  
            [self.provBtn setTitle:[NSString stringWithFormat:@"%@_%@",curSelectProvCode,curProviceVO.prvname] forState:UIControlStateNormal];
        }
    }
    [self drawProbLabel];
    //预警信息提醒，报警空间、网络状况
    float diskSpace= [SystemUtils getFreeDiskspace];
    float alamSpace = 0;
    if (nil != userVO.alamMinSpace) {
        @try
        {
            alamSpace = [userVO.alamMinSpace floatValue];
        }@catch(NSException *exp)
        {
            
        }
        
    }
    if (alamSpace > 0) {
        diskSpace = diskSpace - alamSpace;
        if (diskSpace < 0) {
            NSString *hintInfo=[NSString stringWithFormat:@"系统当前可用空间不足：%.2f 兆,请及时清理磁盘空间",alamSpace];
            
            JSNotifier *notify = [[JSNotifier alloc]initWithTitle:hintInfo];
            notify.accessoryView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"NotifyCheck.png"]];
            [notify showFor:5.0];
        }
    }
    

}


//选中问题类别下的采样记录事件
- (void) clickGatherCode:(NSString *)sender
{
    NSString * gatherCode=sender;
    
    for(id tmpView in [ _picImageView subviews ]){
        //找到要删除的子视图的对象
        if([tmpView isKindOfClass:[DefButton class]]){
            DefButton *imgView = (DefButton *)tmpView;
            [imgView removeFromSuperview]; //删除子视图
        }
    }

    for(id tmpView in [_radioImageView subviews]){
        //找到要删除的子视图的对象
        if([tmpView isKindOfClass:[DefButton class]]){
            DefButton *imgView = (DefButton *)tmpView;
            [imgView removeFromSuperview]; //删除子视图
        }
    }    
    
   GatherResult *gatherResultVO=[mdGather qryGatherResultByPk:gatherCode];    
     
    NSString *photoPath=[TokDocManageUtilities getFileDocPath];
    photoPath=[photoPath  stringByAppendingPathComponent:gatherResultVO.loginuser];
    photoPath=[photoPath  stringByAppendingPathComponent:gatherResultVO.projcode];
    photoPath = [photoPath stringByAppendingString:@"_"];
    photoPath = [photoPath stringByAppendingString:curSelectPjectName];
    photoPath=[photoPath  stringByAppendingPathComponent:gatherResultVO.loginuser];
    photoPath=[photoPath  stringByAppendingPathComponent:gatherResultVO.pccode];
    photoPath=[photoPath  stringByAppendingPathComponent:gatherResultVO.gathercode];
   
    //    NSLog(@"the photoPath is %@",photoPath);
    NSFileManager *fileManager = [NSFileManager defaultManager];
 
    NSError *error = nil;
    NSArray *fileList = [[NSArray alloc] init];
    
    
    //添加图片至图片区
    NSString *picturePath=[photoPath  stringByAppendingPathComponent:@"picture"];
    //fileList便是包含有该文件夹下所有文件的文件名及文件夹名的数组
    fileList = [fileManager contentsOfDirectoryAtPath:picturePath error:&error];
    int imageCount=0;
    for(NSString *imageName in fileList){
        if([imageName hasSuffix:@"png"]){
            NSString *tempStr=[picturePath stringByAppendingPathComponent:imageName];
            NSDictionary *attributes = [[NSFileManager defaultManager] fileAttributesAtPath:tempStr traverseLink:NO];
            BOOL isDirectory=[[attributes objectForKey:NSFileType] isEqualToString:NSFileTypeDirectory];
            if (!isDirectory) {
                NSString *filePath=[picturePath stringByAppendingPathComponent:imageName];
                NSData *myData=[fileManager contentsAtPath:filePath];
                UIImage *myImage=[UIImage imageWithData:myData];
                [self addImage2View:myImage imageCount:imageCount gatherCode:gatherCode];
                imageCount++;
            }
        }
    }
    
    //添加录音至录音区
    
    //添加图片至图片区
    NSString *radioPath=[photoPath  stringByAppendingPathComponent:@"radio"];
    //fileList便是包含有该文件夹下所有文件的文件名及文件夹名的数组
    fileList = [fileManager contentsOfDirectoryAtPath:radioPath error:&error];
    int radioCount=0;
    for(NSString *radioName in fileList){
        if([radioName hasSuffix:@"caf"]){
            NSString *tempStr=[radioPath stringByAppendingPathComponent:radioName];
            NSDictionary *attributes = [[NSFileManager defaultManager] fileAttributesAtPath:tempStr traverseLink:NO];
            BOOL isDirectory=[[attributes objectForKey:NSFileType] isEqualToString:NSFileTypeDirectory];
            if (!isDirectory) {
                NSString *filePath=[radioPath stringByAppendingPathComponent:radioName];
                [self addRadio2View:filePath radioCount:radioCount];
                radioCount++;
            }
        }
    }
}

-(void) afterSelectGatherCode:(NSString *)gatherCode{
    for(id tmpView in [ _picImageView subviews ]){
        //找到要删除的子视图的对象
        if([tmpView isKindOfClass:[DefButton class]]){
            DefButton *imgView = (DefButton *)tmpView;
            [imgView removeFromSuperview]; //删除子视图
        }
    }
    
    for(id tmpView in [_radioImageView subviews]){
        //找到要删除的子视图的对象
        if([tmpView isKindOfClass:[DefButton class]]){
            DefButton *imgView = (DefButton *)tmpView;
            [imgView removeFromSuperview]; //删除子视图
        }
    }
    
    GatherResult *gatherResultVO=[mdGather qryGatherResultByPk:gatherCode];
    //设置备注说明
    self.questTextView.text=gatherResultVO.remark;
    
    NSString *photoPath=[TokDocManageUtilities getFileDocPath];
    photoPath=[photoPath  stringByAppendingPathComponent:gatherResultVO.loginuser];
    photoPath=[photoPath  stringByAppendingPathComponent:gatherResultVO.projcode];
    photoPath = [photoPath stringByAppendingString:@"_"];
    photoPath = [photoPath stringByAppendingString:curSelectPjectName];
    photoPath=[photoPath  stringByAppendingPathComponent:gatherResultVO.loginuser];
    photoPath=[photoPath  stringByAppendingPathComponent:gatherResultVO.pccode];
    photoPath=[photoPath  stringByAppendingPathComponent:gatherResultVO.gathercode];
    
    //    NSLog(@"the photoPath is %@",photoPath);
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    NSError *error = nil;
    NSArray *fileList = [[NSArray alloc] init];
    
    
    //添加图片至图片区
    NSString *picturePath=[photoPath  stringByAppendingPathComponent:@"picture"];
    //fileList便是包含有该文件夹下所有文件的文件名及文件夹名的数组
    fileList = [fileManager contentsOfDirectoryAtPath:picturePath error:&error];
    int imageCount=0;
    for(NSString *imageName in fileList){
        if([imageName hasSuffix:@"png"]){
            NSString *tempStr=[picturePath stringByAppendingPathComponent:imageName];
            NSDictionary *attributes = [[NSFileManager defaultManager] fileAttributesAtPath:tempStr traverseLink:NO];
            BOOL isDirectory=[[attributes objectForKey:NSFileType] isEqualToString:NSFileTypeDirectory];
            if (!isDirectory) {
                NSString *filePath=[picturePath stringByAppendingPathComponent:imageName];
                NSData *myData=[fileManager contentsAtPath:filePath];
                UIImage *myImage=[UIImage imageWithData:myData];
                [self addImage2View:myImage imageCount:imageCount gatherCode:gatherCode];
                imageCount++;
            }
        }
    }
    
    //添加录音至录音区
    
    //添加图片至图片区
    NSString *radioPath=[photoPath  stringByAppendingPathComponent:@"radio"];
    //fileList便是包含有该文件夹下所有文件的文件名及文件夹名的数组
    fileList = [fileManager contentsOfDirectoryAtPath:radioPath error:&error];
    int radioCount=0;
    for(NSString *radioName in fileList){
        if([radioName hasSuffix:@"caf"]){
            NSString *tempStr=[radioPath stringByAppendingPathComponent:radioName];
            NSDictionary *attributes = [[NSFileManager defaultManager] fileAttributesAtPath:tempStr traverseLink:NO];
            BOOL isDirectory=[[attributes objectForKey:NSFileType] isEqualToString:NSFileTypeDirectory];
            if (!isDirectory) {
                NSString *filePath=[radioPath stringByAppendingPathComponent:radioName];
                [self addRadio2View:filePath radioCount:radioCount];
                radioCount++;
            }
        }
    }

    
    
}

-(void) addImage2View:(UIImage *) image imageCount:(float) imageCount gatherCode:(NSString*)gatherCode{
    float photoWidth=0.0f;
    //imageView宽度
    float width = 145.0f;
    //imageView高度
    float height = 110.0f;
    //列间距，即左右间隔
    float columnGap = 10.0f;
    float originalX=columnGap+photoWidth+(width+columnGap)*imageCount;
    float originaly=10.0f;
    DefButton  *imageButton = [[DefButton alloc] initWithFrame:CGRectMake(originalX,originaly, width, height)] ;
    [imageButton setImage:image forState:UIControlStateNormal];
    //为按钮添加UITouch事件
    [imageButton addTarget:self action:@selector(clickPhoto:) forControlEvents:UIControlEventTouchUpInside];
    imageButton.backgroundColor = [UIColor whiteColor];
    [imageButton setBtnCode:gatherCode];
    [_picImageView addSubview:imageButton];
    [imageButton release];
    imageCount=++imageCount;
    float photoViewWidth=photoWidth+(width+columnGap)*imageCount;
    _picImageView.contentSize = CGSizeMake(photoViewWidth,150);
    
}

-(void) addRadio2View:(NSString *)radioFilePath radioCount:(float)radioCount{
    float photoWidth=0.0f;
    //imageView宽度
    float width = 145.0f;
    //imageView高度
    float height = 110.0f;
    //列间距，即左右间隔
    float columnGap = 10.0f;
    float originalX=columnGap+photoWidth+(width+columnGap)*radioCount;
    float originaly=10.0f;
        
    //先把图片转成NSData
    UIImage *image =[UIImage imageNamed:@"sound_btn.png"];
    //设置图片为背景
    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
        
    DefButton  *imageButton = [[DefButton alloc] initWithFrame:CGRectMake(originalX,originaly, width, height)] ;
    [imageButton setImage:image forState:UIControlStateNormal];
    [imageButton setBtnName:radioFilePath];
    //为按钮添加UITouch事件
    [imageButton addTarget:self action:@selector(clickRadio:) forControlEvents:UIControlEventTouchUpInside];
    imageButton.backgroundColor = [UIColor whiteColor];
    [_radioImageView addSubview:imageButton];
    [imageButton release];
    radioCount=++radioCount;
    float photoViewWidth=photoWidth+(width+columnGap)*radioCount;
    _radioImageView.contentSize = CGSizeMake(photoViewWidth,150); 
}

//当触摸图片时，响应该方法
- (void)clickPhoto:(UIButton *)button{
    DefButton *btn=(DefButton *)button;
    NSString * gatherCode=btn.btnCode;
    GatherResult *gatherResultVO=[mdGather qryGatherResultByPk:gatherCode];

    
    NSString *saveFilePath = [TokDocManageUtilities getFileDocPath];
    saveFilePath = [saveFilePath stringByAppendingPathComponent:[userVO loginuser]];
    saveFilePath = [saveFilePath stringByAppendingPathComponent:gatherResultVO.projcode];
    saveFilePath = [saveFilePath stringByAppendingString:@"_"];
    saveFilePath = [saveFilePath stringByAppendingString:curSelectPjectName];
    saveFilePath = [saveFilePath  stringByAppendingPathComponent:gatherResultVO.loginuser];
    saveFilePath = [saveFilePath stringByAppendingPathComponent:gatherResultVO.pccode];
    saveFilePath = [saveFilePath stringByAppendingPathComponent:gatherCode];
    saveFilePath = [saveFilePath stringByAppendingPathComponent:@"picture"];
    PhotoDataSource *dataSource_ = [[PhotoDataSource alloc] init:saveFilePath];
    KTPhotoScrollViewController *newController = [[KTPhotoScrollViewController alloc]
                                                  initWithDataSource:dataSource_
                                                  andStartWithPhotoAtIndex:index];
    [self presentModalViewController:newController animated:YES];
    [newController release];
}

//当触摸录音时，响应该方法
- (void)clickRadio:(UIButton *)button{
    DefButton* cls = (DefButton*)button;
    NSLog(@"the file paht is %@",cls.btnName);
    NSURL *url = [NSURL fileURLWithPath:cls.btnName];
    
    if (self.avPlay.playing) {
        [self.avPlay stop];
    }
    AVAudioPlayer *player = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];
    //    UIImage *image =[UIImage imageNamed:@"sound.gif"];
    //    [button setImage:image forState:UIControlStateNormal];
    self.avPlay = player;
    [player release];
    [self.avPlay play];
}


//省份选择后过滤事件
- (void)afterSelectItem:(NSString *) cellKey tag :(int) tag{
    NSLog(@"the select index is %@",cellKey);
    if(tag==dd1.tag){
      
        [dd2 removeFromSuperview];
        dd2 = [[Combox alloc] initWithFrame:CGRectMake(95, 66, 643, 60)];
        curSelectProvCode=[provKeyValue objectForKey:cellKey];
        NSMutableDictionary *projDict=[mdProject qryProjectByPkPrvcode:curSelectProvCode];
        NSArray *projVOs=[projDict allValues];
        NSMutableArray *projMutiArr=[[NSMutableArray alloc] init];
        for(int i=0;i<[projDict count];i++){
            ProjectVO *projectVO = [projVOs objectAtIndex:i];
            [projMutiArr addObject:[projectVO projname]];
            [projKeyKeyValue setObject:[projectVO projcode] forKey:[projectVO projname]];
            [ dd2.textField setTitle:[projMutiArr objectAtIndex:0] forState: UIControlStateNormal ];
        }
        dd2.tableArray = projMutiArr;
        dd2.delegate=self;
        [_contentScrollView addSubview:dd2];
    }else if(tag==dd2.tag){
        
        curSelectPjectCode=[projKeyKeyValue objectForKey:cellKey];
        
        // 删除原有问题说明
        for(id tmpView in [ _probClsLabel subviews ]){
            //找到要删除的子视图的对象
            if([tmpView isKindOfClass:[MyLabel class]]){
                MyLabel *imgView = (MyLabel *)tmpView;
                [imgView removeFromSuperview]; //删除子视图
            }
        }
        
        
        [self drawProbLabel];
        
    }
}

- (void)viewDidUnload
{
    [self setHintInfoLabel:nil]; 
    [self setContentScrollView:nil];
    [self setProvinceLabel:nil];
    [self setProjectLabel:nil];
    [self setProbClsLabel:nil]; 
    [self setPicImageView:nil];
    [self setRadioImageView:nil];  
    [self setQuestTextView:nil];
    
    [self setRadioImageView:nil];
    [self setProvBtn:nil];
    [self setProjBtn:nil];
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{ 
	return YES;
}

//删除关闭的项目的所有采样记录
-(void)removeCloseProjFile{
   
    //查询关闭的项目
    NSMutableDictionary *dicprojs = [mdProject qryProjectBySqlWhere:@" status > 0"];
    if(nil == dicprojs)
    {
        return;
    }
    
    //获取项目目录
     NSString *docPhotoPath = [TokDocManageUtilities getFileDocPath];
    
    if ([TokDocManageUtilities isExistWithDocPath:docPhotoPath])
   {
        NSString *user_path = [docPhotoPath stringByAppendingPathComponent:[userVO loginuser]];
        NSMutableArray *proj_codes = [[NSMutableArray alloc]initWithCapacity:[dicprojs count]];
        for (ProjectVO *p_vo in [dicprojs allValues]) {
            [proj_codes addObject:[p_vo projcode]];
            NSString *proj_name = [[NSString alloc] initWithFormat:@"%@_%@",[p_vo projcode],[p_vo projname]];
            NSString *proj_doc_path = [user_path stringByAppendingPathComponent:proj_name];
            if ([TokDocManageUtilities isExistWithDocPath:proj_doc_path])
            {
                [TokDocManageUtilities deleteDictionaryAtPath:proj_doc_path];
            }

            [proj_name release];
            proj_name = nil;
//            [proj_doc_path release];
//            proj_doc_path = nil;
            

            
        }
       //删除项目采样文件记录,删除项目采样记录
       [mdGather deleteGatherResultWithProjectCode:proj_codes loginuser:[userVO loginuser]];
       //删除项目记录
       [mdProject deleteProjectsWithProjCodes:proj_codes loginUser:[userVO loginuser]];
       [proj_codes release];

    }
    

//    [docPhotoPath release];
//    docPhotoPath = nil;
    
    [dicprojs release];
    dicprojs = nil;
    
}

- (IBAction)logoutBtn:(id)sender {
    [self removeCloseProjFile];
     [self.presentingViewController dismissModalViewControllerAnimated:YES];
}

- (void)refreshTccInfo {
	RequestTccInfo *reqeustProv=[[RequestTccInfo alloc] init];
    //构建服务器信息
    NSString *serverInfo=userVO.serverIP;
    serverInfo=[serverInfo stringByAppendingFormat:@":%@",userVO.serverPort ];
    reqeustProv.serverInfo = serverInfo;
    //同步最新用户密码
    [reqeustProv UserSynchronous:userVO.loginuser pwd:userVO.pwd];
    //获取省份信息
    if(mdProvince==nil){
        mdProvince=[[MDProvince alloc] init];
    }
    NSArray *provinceVos= [reqeustProv getProvinceInfo:userVO.loginuser pwd:userVO.pwd];
    if(nil != provinceVos && provinceVos.count > 0) {
        //更新本地省份信息
        [mdProvince update:provinceVos];
        //项目信息
        if(mdProject==nil){
            mdProject=[[MDProject alloc] init];
        }
        //根据省份，循环查询项目信息（效率比较低），后续建议改进接口
        for (int i = 0; i < provinceVos.count; i++) {
            ProviceVO *prvo = [provinceVos objectAtIndex:i];
            /*待补充*/
            NSArray *projectVOs=[reqeustProv GetProjectInfoByProvince:userVO.loginuser pwd:userVO.pwd projcode:nil provcode:[prvo prvcode]];
            [mdProject update:projectVOs];
        }
    }
    NSArray *probClsVos=[reqeustProv getQuestTypeWithUser:userVO.loginuser];
    
    //更新问题分类至本地，如果本地没有，则新增
    MDProbCls *mdProbCl=[[MDProbCls alloc] init];
    if(nil != probClsVos && probClsVos.count > 0){
        [mdProbCl update:probClsVos];
    }

    [loadingView removeFromSuperview];
}

//刷新数据
- (IBAction)refreshBtn:(id)sender {
    loadingView = [LoadingView loadingViewInView:self.view title:@"正在刷新数据，请稍后，刷新完成后，对话框会自动消失。"];
	[loadingView showWhileExecuting:@selector(refreshTccInfo) onTarget:self withObject:nil animated:YES];
}

//采样
- (IBAction)addEvidenceBtn:(id)sender {
    AddViewController *addEvidenceViewCtrl=[[AddViewController alloc] initWithNibName:@"AddViewController" bundle:nil];
    [addEvidenceViewCtrl setUserVO:userVO];
    [self presentModalViewController:addEvidenceViewCtrl animated:YES];

}

-(int) zipFile{
    NSString *docPhotoPath = [TokDocManageUtilities getFileDocPath];
    //    docPhotoPath = [docPhotoPath stringByAppendingPathComponent:[userVO loginuser]];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    int isZiped=2;
    BOOL isDir=NO;
    if ([fileManager fileExistsAtPath:docPhotoPath isDirectory:&isDir] && isDir){
        //获取所有项目文件夹名称
        NSArray *projPaths=[fileManager contentsOfDirectoryAtPath:docPhotoPath error:nil];
        
        for(NSString *projName in projPaths){
            NSString *longPath = [docPhotoPath stringByAppendingPathComponent:projName];
            if([fileManager fileExistsAtPath:longPath isDirectory:&isDir] && isDir){
                ZipArchive *archiver = [[ZipArchive alloc] init];
                
                //文件按照项目打包
                NSString *archivePath = [longPath stringByAppendingString:@".zip"];
                [archiver CreateZipFile2:archivePath];
                NSString *projFilePath=[docPhotoPath stringByAppendingPathComponent:projName];
                NSArray *subpaths = [fileManager subpathsAtPath:projFilePath];
                for(NSString *path in subpaths){
                    if(![path hasSuffix:@"DS_Store"]){
                        NSLog(@"longPath %@",path);
                        NSArray *values=[path componentsSeparatedByString:@"/"];
                        //截取路径长度，如果等于4，表明最后一级是记录主键
                        if([values count]>=4){
                            NSString *pkGather=[values objectAtIndex:3];
                            //如果记录未提交，则压缩文件，否则不做处理
                            if(![mdGather isCommit:pkGather]){
                                isZiped=0;
                                NSString *longPath = [docPhotoPath stringByAppendingPathComponent:projName];
                                longPath = [longPath stringByAppendingPathComponent:path];
                                //NSLog(@"longPath %@",longPath);
                                //只打包具体文件，不打包文件夹
                                if([fileManager fileExistsAtPath:longPath isDirectory:&isDir] && !isDir){
                                    [archiver addFileToZip:longPath newname:path];
                                }
                            }
                        }
                    }
                }
                BOOL successCompressing = [archiver CloseZipFile2];
                if(successCompressing){
                    isZiped=0;
                }else{
                    isZiped=1;
                }
            }
        }
    }
    return isZiped;
}



-(BOOL) uploadFile{
    BOOL isuploaded=FALSE;
    //以下是文件上传
//    NSString *url=[NSString stringWithFormat:@"http://124.65.69.158:6002/UploadForIOS/upload.ashx"];
    NSString *url=[[NSString alloc]initWithFormat:@"http://%@:%@/upload.ashx",userVO.serverIP,userVO.serverPort];
    
    ASIFormDataRequest *form = [[[ASIFormDataRequest alloc]
                                 initWithURL:[NSURL URLWithString:url]] autorelease];
    [form setTimeOutSeconds:60.0];
    form.delegate = self;
    
    //分界线的标识符
    NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x";
    //分界线 --AaB03x
    NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
    //结束符 AaB03x--
    NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
    NSString *docPhotoPath = [TokDocManageUtilities getFileDocPath];
    NSString *file=[docPhotoPath stringByAppendingPathComponent:[userVO loginuser]];
    file=[file stringByAppendingString:@".zip"];
    //    NSLog(@"the upload file is :%@",file);
    NSData* data = [NSData dataWithContentsOfFile:file];;
    //http body的字符串
    NSMutableString *body=[[NSMutableString alloc]init];
    //声明结束符：--AaB03x--
    NSString *end=[[NSString alloc]initWithFormat:@"\r\n%@",endMPboundary];
    //声明myRequestData，用来放入http body
    [body appendFormat:@"Content-Disposition: form-data "];
    NSMutableData *myRequestData=[NSMutableData data];
    //将body字符串转化为UTF8格式的二进制
    [myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
    //将image的data加入
    [myRequestData appendData:data];
    //加入结束符--AaB03x--
    [myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
    //设置HTTPHeader中Content-Type的值
    NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
    [form setRequestMethod:@"POST"];
    NSString * fileName=[[NSString alloc]initWithFormat:@"%@.zip",userVO.loginuser];
    
    [form setPostValue:fileName forKey:@"file"];
    [form setData:data forKey:@"file"];
    //            [form setUploadProgressDelegate:uploadProgress];
    [form setShowAccurateProgress:YES];
    [form setDelegate:self];
    [form startAsynchronous];
    NSError *error = [form error];
    if (!error) {
        NSString *response = [form responseString];
        NSLog(@"响应信息：%@",response);
        isuploaded=TRUE;
    }
    return isuploaded;
}

- (void)myTask {
	NSString *showMsg=nil;
    int isziped=[self zipFile];
    if(isziped==0){
        BOOL isupload=[self uploadFile];
        if(isupload){
            showMsg=@"采样记录上传成功";
            //更改项目下所有采样记录为提交态
            [mdGather updateResultStatus:curSelectProvCode projCode:curSelectPjectCode loginUser:userVO.loginuser];
        }else{
            showMsg=@"采样记录上传失败";
        }
    }else if(isziped==1){
        showMsg=@"文件压缩失败";
    }else if(isziped==2){
        showMsg=@"没有需要提交的采样记录";
    }
    [loadingView removeFromSuperview];
}

//提交
- (IBAction)commitBtn:(id)sender{
    if(curSelectPjectCode==nil){
        UIAlertView* alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请先选择项目项目" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
        [alert show];
        return ;
    }
    loadingView = [LoadingView loadingViewInView:self.view title:@"正在上传采样记录，请稍后，提交完成后，对话框会自动消失。"];
	[loadingView showWhileExecuting:@selector(myTask) onTarget:self withObject:nil animated:YES];
    
}
- (void)dealloc {
    [_hintInfoLabel release]; 
    [_contentScrollView release];
    [_probClsLabel release];
    [_provinceLabel release];
    [_projectLabel release]; 
    [_picImageView release];
    [_radioImageView release]; 
    [_questTextView release]; 
    [_radioImageView release];
    [_provBtn release];
    [_projBtn release];
    [super dealloc];
}

#pragma mark - provoice、project、gatherCode selected event

- (IBAction)provBtnClick:(id)sender {
    
    PropoverProvViewController *provView=[[PropoverProvViewController alloc] initViewWithCode:userVO.loginuser];
    
    provView.delegate=self;
    
    FPPopoverController *popover = [[FPPopoverController alloc] initWithViewController:provView];
    [provView release];
    
    //popover.arrowDirection = FPPopoverArrowDirectionAny;
    popover.tint = FPPopoverDefaultTint;
    
    if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
    {
        popover.contentSize = CGSizeMake(300, 300);
    }
    popover.arrowDirection = FPPopoverArrowDirectionAny;
    
    //sender is the UIButton view
    [popover presentPopoverFromView:sender];
    popoverCtrl=popover;
 
}


- (IBAction)projBtnClick:(id)sender {
    
    if(curSelectProvCode==nil){
        UIAlertView* alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请先选择省份" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
        [alert show];
        return ;
    }
    ProjPoverProjViewController *provView=[[ProjPoverProjViewController alloc] initViewWithCode:curSelectProvCode];
    
    provView.delegate=self;
    
    FPPopoverController *popover = [[FPPopoverController alloc] initWithViewController:provView];
    [provView release];
    
    //popover.arrowDirection = FPPopoverArrowDirectionAny;
    popover.tint = FPPopoverDefaultTint;
    
    if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
    {
        popover.contentSize = CGSizeMake(300, 300);
    }
    popover.arrowDirection = FPPopoverArrowDirectionAny;
    
    //sender is the UIButton view
    [popover presentPopoverFromView:sender];
    popoverCtrl=popover;
    
}


// 点击问题类别右上角次数响应事件
- (void)clickLable:(UILabel *)uiLabel {
    MyLabel *myLabel= (MyLabel*)uiLabel;
    
    if(curSelectProvCode==nil || curSelectPjectCode==nil){
        UIAlertView* alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请先选择省份" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
        [alert show];
        return ;
    }
    PopoverViewController *controller = [[PopoverViewController alloc]initViewWithCode:curSelectPjectCode probClsCode:[myLabel labelCode]  prvcode:curSelectProvCode loginUser:userVO.loginuser];
    
    FPPopoverController *popover = [[FPPopoverController alloc] initWithViewController:controller];
    controller.delegate=self;
    [controller release];
    
    //popover.arrowDirection = FPPopoverArrowDirectionAny;
    popover.tint = FPPopoverDefaultTint;
    
    if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
    {
        popover.contentSize = CGSizeMake(300, 400);
    }
    popover.arrowDirection = FPPopoverArrowDirectionAny;
    
    //sender is the UIButton view
    [popover presentPopoverFromView:uiLabel];
    popoverCtrl=popover;
}



#pragma mark - PopoverViewSelectDelegate


- (void)afterCellSelected:(NSString *) cellCode cellName:(NSString *) cellName tag :(int) tag{
    
    [popoverCtrl dismissPopoverAnimated:YES];
    NSString * cellTitle=cellCode;
    cellTitle=[cellTitle stringByAppendingString:@"_"];
    cellTitle=[cellTitle stringByAppendingString:cellName];
    if(tag==1){ 
        [self.provBtn setTitle:cellTitle forState:UIControlStateNormal];
        self.curSelectProvCode=cellCode;
    }else if(tag==2){
        [self.projBtn setTitle:cellTitle forState:UIControlStateNormal];
        self.curSelectPjectCode=cellCode;
        self.curSelectPjectName=cellName;
        [self drawProbLabel];
        
    }else if(tag==3){
        [self afterSelectGatherCode:cellCode];
    } 
}


@end
